/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-05-18
*/
package com.rzico.order.controller.admin;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Refunds;
import com.rzico.account.model.Attach;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Chef;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Product;
import com.rzico.basics.service.ChefService;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.ProductService;
import com.rzico.core.entity.*;
import com.rzico.core.service.*;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.exception.CustomException;
import com.rzico.order.entity.*;
import com.rzico.order.enumx.AskforStatusEnum;
import com.rzico.order.enumx.ReturnStatusEnum;
import com.rzico.order.enumx.ShippingStatusEnum;
import com.rzico.order.plugin.JDPluginService;
import com.rzico.order.service.*;
import com.rzico.util.DateUtils;
import com.rzico.util.HttpUtils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.*;
import net.sf.jasperreports.engine.JRException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;

/**
 * 退货申请单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-05-18
 */
@Api(description = "退货申请单接口")
@RestController
@RequestMapping("/admin/askfor")
public class AskforAdminController extends BaseController {

    @Value("${rzico.filePath.windows}")
    private String windowsFilePath;

    @Value("${rzico.filePath.linux}")
    private String linuxFilePath;

    @Autowired
    private AskforService askforService;
    @Autowired
    private AskforItemService askforItemService;

    @Autowired
    private SysSequenceService sysSequenceService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private ProductService productService;

    @Autowired
    private AskforLogService askforLogService;

    @Autowired
    private ReturnService returnService;

    @Autowired
    private ShippingService shippingService;

    @Autowired
    private SysOfficeService sysOfficeService;

    @Autowired
    protected SysEmployeeService sysEmployeeService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysReportService sysReportService;

    @Autowired
    protected SysUserService sysUserService;

    @Autowired
    protected WarehouseService warehouseService;

    @Autowired
    private ChefService chefService;

    @Autowired
    private SysMchService sysMchService;

//  @Autowired
//  private JDPluginService jDPluginService;

    /**
     * 分页查询退货申请单
     *
     * @return
    */
    @ApiOperation("分页查询退货申请单")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "companyId", value = "所属企业", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "memberId", value = "客户Id", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "orderSn", value = "订单号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "productId", value = "商品ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "收货电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态", dataType = "Integer", paramType = "query")
    })

    public CommResult<Askfor> list(Date startDate, Date endDate,Long companyId,Integer status,Long memberId,Long productId,String orderSn,String phone, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
            params.put("startDate", org.apache.commons.lang3.time.DateUtils.truncate(startDate, Calendar.DATE));
        }
        if (endDate!=null){
            params.put("endDate", org.apache.commons.lang3.time.DateUtils.addMilliseconds(org.apache.commons.lang3.time.DateUtils.addDays(endDate,1),-1));
        }
        if (null != memberId){
            params.put("memberId", memberId);
        }
        if (null != companyId){
            params.put("companyId", companyId);
        }
        if (null != orderSn){
            params.put("orderSn", orderSn);
        }
        if (null != productId){
            Product product = productService.findById(productId);
            params.put("goodsId", product.getGoodsId());
        }
        if (null != phone){
            params.put("phone", phone);
        }

        params.put("deleted", false);

        if (null != status){
            params.put("status", status);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (!sysMch.getMchType().equals(0))  {
            params.put("enterpriseId", enterprise.getId());
        }

        //非管理员都启用数据权限
//        SysUser sysUser = sysUserService.getCurrent();
//        if (!sysUserService.isAdmin(sysUser)) {
//            params.put("dataScopeId",sysUser.getId());
//        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Askfor> list = askforService.selectList(params);
        PageResult<Askfor> pageResult = new PageResult<Askfor>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }


    /**
     * 统计末完成退款单数
     *
     * @return
     */
    @ApiOperation("统计末完成退款单数")
    @PostMapping("/summary")
    public CommResult<Order> summary() {

        Enterprise enterprise = enterpriseService.getCurrent();

        Map<String,Object> data = new HashMap<>();
        Map<String,Object> params = new HashMap<>();

       //申请状态(0:未确认,1:已同意,2:已寄回,3.待退款,4.已完成,5.已关闭)

        params.put("status",0);
        params.put("enterpriseId",enterprise.getId());
        params.put("deleted",false);
        data.put("unconfirm",askforService.selectRowCount(params));

        params.clear();
        params.put("status",1);
        params.put("enterpriseId",enterprise.getId());
        params.put("deleted",false);
        data.put("confirmed",askforService.selectRowCount(params));

        params.clear();
        params.put("status",2);
        params.put("enterpriseId",enterprise.getId());
        params.put("deleted",false);
        data.put("shipped",askforService.selectRowCount(params));

        params.clear();
        params.put("status",3);
        params.put("enterpriseId",enterprise.getId());
        params.put("deleted",false);
        data.put("unRefund",askforService.selectRowCount(params));

        return CommResult.success(data);

    }


    /**
     * 查询单条退货申请单
     *
     * @return
    */
    @ApiOperation("查询单条退货申请单")
    @GetMapping("/find/{id}")
    public CommResult<Askfor> find(@PathVariable String id) {
        Askfor result = askforService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("askfor",result);

        Map<String,Object> params = new HashMap<>();
        params.put("askforId",result.getId());
        result.setItemList(askforItemService.selectList(params));

        if (result.getOfficeId()!=null && !"".equals(result.getOfficeId())) {
            SysOffice sysOffice = sysOfficeService.selectByPrimaryKey(result.getOfficeId());
            if (sysOffice!=null) {
                data.put("officeName", sysOffice.getName());
            } else {
                data.put("officeName", "无");
            }
        } else {
            data.put("officeName", "无");
        }

        if (result.getOperatorId()!=null) {
            SysEmployee sysUser = sysEmployeeService.selectByPrimaryKey(result.getOperatorId());
            if (sysUser!=null) {
                data.put("operatorName", sysUser.getName());
            } else {
                data.put("operatorName", "无");
            }
        } else {
            data.put("operatorName", "无");
        }

        if (result.getMemberId()!=null) {
            Member member = memberService.selectByPrimaryKey(result.getMemberId());
            data.put("memberName", member.getName());
        }

        if (result.getChefId()!=null) {
            Chef chef = chefService.selectByPrimaryKey(result.getChefId());
            data.put("chefName",chef.getName());
        }


        params.clear();
        params.put("orderId",result.getId());
        params.put("orderType","askfor");
        data.put("files",sysFileService.selectList(params));

        Map<String,Object> logPrms = new HashMap<>();
        logPrms.put("askforId",id);
        logPrms.put("sortField","id");
        logPrms.put("sortType","desc");
        data.put("askforLog",askforLogService.selectList(logPrms));


        return CommResult.success(data);

    }

    /**
     * 批量删除退货申请单
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除退货申请单", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除退货申请单,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Askfor> del(@PathVariable String ids) {

        try {
            askforService.deleteByIds(ids.split(","));
        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }
        return CommResult.success();
    }

    /**
     * 更新退货申请单
     *
     * @param askfor
     * @return
     */
    @Log(desc = "更新退货申请单", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新退货申请单")
    @PostMapping("/update")
    public CommResult<Askfor> update(@RequestBody Askfor askfor) {
        int affectCount = askforService.updateByPrimaryKeySelective(askfor);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Askfor result = askforService.findById(askfor.getId());
        return CommResult.success(result);
    }

    /**
     * 同意退货
     *
     * @param id
     * @return
     */
    @ApiOperation("同意退货")
    @PostMapping("/confirm/{id}")
    public CommResult<Askfor> confirm(@PathVariable Long id,Long shopId) {

        Assert.notNull(id, "订单编码为空");

        //判断京东商品是否可以退货

//        List<Map<String, Object>> mapList = jDPluginService.checkAskfor(id);
//        boolean jdCanAfterSale = true;
//        StringBuffer skuIds = new StringBuffer();
//        for (Map<String, Object> map : mapList) {
//            if (map.get("afterSale").equals(false)) {
//                jdCanAfterSale = false;
//                skuIds.append(map.get("skuId").toString() + ",");
//            } else if (-1 == new BigDecimal(map.get("afterSaleNum").toString()).compareTo(new BigDecimal(map.get("num").toString()))) {
//                jdCanAfterSale = false;
//                skuIds.append(map.get("skuId").toString() + ",");
//            } else if (!map.get("serviceType").toString().contains("10")) {
//                jdCanAfterSale = false;
//                skuIds.append(map.get("skuId").toString() + ",");
//            } else if (!map.get("saleDis").toString().contains("40")) {
//                jdCanAfterSale = false;
//                skuIds.append(map.get("skuId").toString() + ",");
//            }
//        }
//        if (!jdCanAfterSale) {
//            return CommResult.error("商品" + skuIds.toString() + "不可申请售后");
//        }

        try {
            int affectCount = askforService.confirm(id);
            if (affectCount <= 0) {
                return CommResult.error();
            }

            Askfor result = askforService.findById(id);

            List<Refunds> refundsList = askforService.refund(id, sysSequenceService.generate("refunds"));
            for (Refunds refunds:refundsList) {
                //TODO发送退款通知
                Attach attachQueue = new Attach();
                attachQueue.setCode("0000");
                attachQueue.setId(String.valueOf(refunds.getId()));
                attachQueue.setQueue("queue.refunds.submit");
                Message message = MessageBuilder
                        .withBody(JSON.toJSONString(attachQueue).getBytes())
                        .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                        .build();
                CorrelationData correlationData = new CorrelationData();
                correlationData.setId(UUID.randomUUID().toString());
                logger.info("发送 MQ");
                rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);

            }

            return CommResult.success(result);


        } catch (Exception e) {
            return CommResult.error(e.getMessage());
        }


//        if (!result.getShippingMethod().equals(0) && !result.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_SHIPPED.getId())) {
//
//            result.setItemList(askforItemService.getItemList(result.getId()));
//            Map<String,Object> params = new HashMap<>();
//            params.put("orderId",result.getOrderId());
//            if (shopId==null) {
//                List<Warehouse> warehouseList = warehouseService.selectList(params);
//                for (Warehouse warehouse : warehouseList) {
//                    if (shopId != null && !shopId.equals(warehouse.getShopId())) {
//                        shopId = null;
//                        break;
//                    }
//                    shopId = warehouse.getShopId();
//                }
//            }
//
//            if (shopId!=null) {
//                askforService.received(id,shopId, org.apache.commons.lang3.time.DateUtils.truncate(new Date(),Calendar.DATE),sysSequenceService.generate("warehouse"));
//            }
//
//        }

    }

//    /**
//     * 退货确认
//     *
//     * @param id
//     * @return
//     */

//    @ApiOperation("退货确认")
//    @PostMapping("/received/{id}")
//    @ApiImplicitParams({@ApiImplicitParam(name = "shopId", value = "退货仓库", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "orderDate", value = "退货日期", dataType = "String", paramType = "query")
//    })
//    public CommResult<Askfor> received(@PathVariable Long id,Long shopId,Date orderDate) {
//        if (shopId==null) {
//            return CommResult.error("请选择退货仓库");
//        }
//        Askfor askfor = askforService.findById(id);
//        askfor.setItemList(askforItemService.getItemList(id));
//        int affectCount = askforService.received(id,shopId,orderDate,sysSequenceService.generate("warehouse"));
//        if (affectCount <= 0){
//            return CommResult.error();
//        }
//        return CommResult.success();
//
//    }


    /**
     * 退货并入库
     *
     * @param id
     * @return
     */

//    @ApiOperation("退货并入库")
//    @PostMapping("/receivedAndAudit/{id}")
//    @ApiImplicitParams({@ApiImplicitParam(name = "shopId", value = "退货仓库", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "orderDate", value = "退货日期", dataType = "String", paramType = "query")
//    })
//    public CommResult<Askfor> receivedAndAudit(@PathVariable Long id,Long shopId,Date orderDate) {
//        if (shopId==null) {
//            return CommResult.error("请选择退货仓库");
//        }
//        Askfor askfor = askforService.findById(id);
//        askfor.setItemList(askforItemService.getItemList(id));
//       /* if (askfor.getShippingMethod().equals(0)) {
//            for (AskforItem askforItem:askfor.getItemList()) {
//                if (askforItem.getTrackingNo()==null) {
//                    return CommResult.error("请寄回再确认");
//                }
//            }
//        }*/
//        int affectCount = askforService.received(id,shopId,orderDate,sysSequenceService.generate("warehouse"));
//        if (affectCount <= 0){
//            return CommResult.error();
//        }
//        return CommResult.success();
//    }


    /**
     * 修改退款金额
     *
     * @param id
     * @return
     */
    @ApiOperation("修改退款金额")
    @PostMapping("/updateOffsetAmount/{id}")
    @ApiImplicitParams({})
    public CommResult<Askfor> updateOffsetAmount(@PathVariable Long id, BigDecimal offsetAmount) {
        Askfor askfor = askforService.findById(id);
        askfor.setOffsetAmount(offsetAmount);

        if (!askfor.getStatus().equals(AskforStatusEnum.ASKFOR_STATUS_SHIPPED.getId())) {
            return CommResult.error("不是待退款状态");
        }

        askforService.updateOffsetAmount(askfor);


        return CommResult.success(askfor);

    }

    /**
     * 确认退款
     *
     * @param id
     * @return
     */
    @ApiOperation("确认退款")
    @PostMapping("/refund/{id}")
    @ApiImplicitParams({})
    public CommResult<Askfor> refund(@PathVariable Long id) {

       // Askfor askfor = askforService.findById(id);

        //检查是否收货完毕
//        Map<String,Object> params = new HashMap<>();
//        params.put("orderId",askfor.getOrderId());
//        List<Shipping> shippingList = shippingService.selectList(params);
//
//        for (Shipping rn:shippingList) {
//            if (!rn.getShippingStatus().equals(ShippingStatusEnum.SHIPPING_STATUS_SEND.getId())
//                    &&
//                !rn.getShippingStatus().equals(ShippingStatusEnum.SHIPPING_STATUS_RECEIVED.getId())
//                    &&
//                !rn.getShippingStatus().equals(ShippingStatusEnum.SHIPPING_STATUS_CANCELED.getId())
//                    &&
//                !rn.getShippingStatus().equals(ShippingStatusEnum.SHIPPING_STATUS_COMPLETE.getId())
//                    ) {
//                return CommResult.error("送货未完成");
//            }
//        }

        //检查是否收货完毕

//        params.put("askforId",id);
//        List<Return> returnList = returnService.selectList(params);
//
//        for (Return rn:returnList) {
//            if (!rn.getShippingStatus().equals(ReturnStatusEnum.RETURN_STATUS_COMPLETE.getId())
//                    &&
//                !rn.getShippingStatus().equals(ReturnStatusEnum.RETURN_STATUS_CANCELED.getId())
//                    &&
//                !rn.getShippingStatus().equals(ReturnStatusEnum.RETURN_STATUS_DISPATCH.getId())
//                    ) {
//                return CommResult.error("退货未完成");
//            }
//        }

        try {
            List<Refunds> refundsList = askforService.refund(id, sysSequenceService.generate("refunds"));
            for (Refunds refunds:refundsList) {
                //TODO发送退款通知
                Attach attachQueue = new Attach();
                attachQueue.setCode("0000");
                attachQueue.setId(String.valueOf(refunds.getId()));
                attachQueue.setQueue("queue.refunds.submit");
                Message message = MessageBuilder
                        .withBody(JSON.toJSONString(attachQueue).getBytes())
                        .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                        .build();
                CorrelationData correlationData = new CorrelationData();
                correlationData.setId(UUID.randomUUID().toString());
                logger.info("发送 MQ");
                rabbitTemplate.convertAndSend("directExchange",attachQueue.getQueue()+".key", message, correlationData);

            }
            return CommResult.success();

        } catch (Exception e) {
            logger.error(e.getMessage());
            return CommResult.error(e.getMessage());
        }

    }

    /**
     * 关闭退款
     *
     * @param id
     * @return
     */
    @ApiOperation("关闭退款")
    @PostMapping("/cancel/{id}")
    @ApiImplicitParams({})
    public CommResult<Askfor> cancel(@PathVariable Long id) {
        try {
            int affectCount = askforService.reject(id);
            if (affectCount <= 0){
                return CommResult.error();
            }
            return CommResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return CommResult.error(e.getMessage());
        }
    }


    /**
     *  订单打印
     *
     * @param id
     * @return
     */
    @ApiOperation("订单打印")
    @GetMapping("/print/{id}")
    public void print(HttpServletRequest request, HttpServletResponse response, @PathVariable String id)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        Askfor order = askforService.selectByPrimaryKey(id);
        if (null == order){
            throw new CustomException("退货单不存在");
        }

        Map<String, Object> param = new HashMap<String, Object>();
        param = HttpUtils.requestParam(request);
        Enterprise enterprise = enterpriseService.getCurrent();
        if (null == enterprise) {
            throw new CustomException("没有开通企业");
        }
        param.put("enterpriseId",enterprise.getId());
        logger.info("打印报表查询参数：{}", param.toString());

        String fileName = enterprise.getMchId()+"_"+order.getSn() + ".jasper";
        //fileName就是sys_report表的id
        SysReport sysReport = sysReportService.selectByPrimaryKey(fileName);

        String filePath = "";
        if (System.getProperty("os.name").contains("Windows")) {
            filePath = windowsFilePath;
        } else if (System.getProperty("os.name").contains("Linux")) {
            filePath = linuxFilePath;
        }
        //检查服务器上是否存在模板
        File file = new File(filePath + File.separator + fileName);
        if (!file.exists()){
            try {
                //不存在，从服务器上下载
                String url = sysReport == null?"":sysReport.getTemplate();
                sysReportService.fileDownLoad(response, url, filePath, fileName);
            } catch (Exception e){
                logger.info("打印模板下载失败");
                throw new CustomException("打印模板下载失败");
            }
        }

        param.put("COMPANY",enterprise.getName());
        param.put("REPORT_NAME", "退货申请单");
        String reportName = "askForPrint";
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT j.*,m.name as member_name,o.name as office_name,e.name as operate_name from (");
        sql.append(" SELECT ");
        sql.append("     a.id,a.member_id,a.office_id,a.operator,a.sn order_sn,a.amount_payable,b.sn,a.consignee,a.phone,a.area_name,a.address,a.order_date,b.price,b.quantity,b.price*b.quantity as amount,b.discount,a.memo,b.name,b.unit,b.spec ");
        sql.append(" FROM wx_askfor a,wx_askfor_item b");
        sql.append(" WHERE a.id=b.askfor_id and a.id = "+id+") j ");
        sql.append(" LEFT OUTER JOIN wx_member m on j.member_id = m.id ");
        sql.append(" LEFT OUTER JOIN sys_office o on j.office_id = o.id ");
        sql.append(" LEFT OUTER JOIN sys_employee e on j.operator = e.id ");

        File file2 = new File(filePath + File.separator + fileName);
        if (!file2.exists()) {
            //下载之后还不存在，就使用classpath路径的模板
            sysReportService.ReportToPdfBySql(reportName, param, sql.toString(), response);
        }else{
            sysReportService.commReportToPdf(filePath, fileName, param, sql.toString(), response);
        }
    }

    /**
     *  订单打印
     *
     * @param id
     * @return
     */
    @ApiOperation("导出订单")
    @GetMapping("/export/{id}")
    public void export(HttpServletRequest request, HttpServletResponse response, @PathVariable String id)
            throws ClassNotFoundException, SQLException, JRException, IOException, IllegalAccessException{
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>订单打印 start<<<<<<<<<<<<<<<<<<<<<<<<<<<");
        Map<String, Object> param = new HashMap<String, Object>();
        Askfor order = askforService.selectByPrimaryKey(id);
        if (null == order){
            throw new CustomException("退货单不存在");
        }

        Enterprise enterprise = enterpriseService.selectByPrimaryKey(order.getEnterpriseId());
        param.put("COMPANY",enterprise.getName());
        param.put("REPORT_NAME", "退货申请单");
        String reportName = "askForPrint";
        StringBuffer sql = new StringBuffer();
        sql.append(" SELECT j.*,m.name as member_name,o.name as office_name,e.name as operate_name from (");
        sql.append(" SELECT a.id,a.member_id,a.office_id,a.operator,a.sn order_sn,b.sn,a.amount_payable,a.consignee, ");
        sql.append("     a.phone,a.area_name,a.address,a.order_date,b.price,b.quantity,b.price*b.quantity as amount,b.discount,a.memo,b.name,b.unit,b.spec ");
        sql.append(" FROM wx_askfor a,wx_askfor_item b ");
        sql.append(" WHERE a.id=b.askfor_id and a.id = "+id+") j ");
        sql.append(" LEFT OUTER JOIN wx_member m on j.member_id = m.id ");
        sql.append(" LEFT OUTER JOIN sys_office o on j.office_id = o.id ");
        sql.append(" LEFT OUTER JOIN sys_employee e on j.operator = e.id ");

        sysReportService.ReportToExcelBySql(reportName, param, sql.toString(), response);
    }

}
